package com.ibm.moa.outmail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ibm.moa.outmail.module.MailInfo;
import com.ibm.moa.outmail.net.HttpManage;
import com.ibm.moa.outmail.net.HttpRequestListener;
import com.ibm.moa.outmail.utils.DBHandler;
import com.ibm.moa.outmail.utils.DensityUtil;
import com.ibm.moa.outmail.utils.ParserRequest;
import com.ibm.moa.outmail.utils.PropertiesUtils;
import com.ibm.moa.outmail.utils.UIEventListener;
import com.ibm.moa.outmail.utils.Utils;
import com.ibm.moa.outmail.view.MyWebView;
import com.ibm.moa.outmail.view.TextImageView;

@SuppressWarnings("deprecation")
public class MailActivity extends BaseActivity implements OnClickListener, AnimationListener, HttpRequestListener {
	LinearLayout markLayout;
	LinearLayout menuLayout;
	TextView titleText;
	RelativeLayout menuSaveBackBT, menuBackBT, menuCancleBT;
	TranslateAnimation showMenuAnimation, hideMenuAnimation;
	ImageView ivBackIV;
	TextImageView ivSend;
	EditText recAddrET, mailCcET, mailBccET, subjectET, contentET;
	MailInfo mailInfo;
	Dialog dialog;
	/** 0新邮件；1回复；2全部回复；3转发；4草稿 */
	int mailType = 0;
	boolean getData = false;
	boolean isSend = false;
	MyWebView preContent;
	String preContentStr = "";

	ImageView recAddrADD, mailccADD, mailBccADD, mail_add_attachment;

	// 附件
	private LinearLayout fujianSwitch, fujianContent;
	private ImageView fujianArrow;

	// 附件数量
	private TextView fujianNum;

	// 附件显示的条目
	private RelativeLayout fujianItem;
	private ListView attListView;
	private List<String> fileList = new ArrayList<String>();

	@SuppressLint("HandlerLeak")
	@SuppressWarnings("unchecked")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (dialog != null && dialog.isShowing()) {
				dialog.dismiss();
			}
			switch (msg.what) {
			case UIEventListener.EVENT_GET_DATA_SUCCESS:
				HashMap<String, Object> map = (HashMap<String, Object>) msg.obj;
				if (map != null) {
					if ("1".equals(map.get("req_code"))) {
						Toast.makeText(MailActivity.this, (String) map.get("req_mess") == null ? "发送成功" : (map.get("req_mess") + ""),
								Toast.LENGTH_SHORT).show();
						if (mailInfo == null) {
							mailInfo = new MailInfo();
						}
						mailInfo.recAddr = recAddrET.getText().toString().trim();
						mailInfo.from = MailApplication.userCode + PropertiesUtils.singlton().getProperty("MAILPATH");
						mailInfo.mailCc = mailCcET.getText().toString().trim();
						mailInfo.mailBcc = mailBccET.getText().toString().trim();
						mailInfo.subject = subjectET.getText().toString().trim();
						mailInfo.plainContent = contentET.getText().toString().trim();
						if (mailType == 1 || mailType == 2 || mailType == 3
								|| (mailType == 4 && mailInfo.preContent != null && !"".equals(mailInfo.preContent))) {
							mailInfo.preContent = "<br/></p>" + preContentStr;
						}
						DBHandler db = new DBHandler(MailActivity.this);
						db.addSendMail(mailInfo);
						if (mailType == 4) {
							ArrayList<Long> times = new ArrayList<Long>();
							times.add(mailInfo.timeMillis);
							db.deleteCaoGao(times);
							MailActivity.this.setResult(RESULT_OK);
						}
						finish();
					} else {
						Toast.makeText(MailActivity.this, (String) map.get("req_mess") == null ? "返回信息错误" : (map.get("req_mess") + ""),
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case UIEventListener.EVENT_GET_DATA_FAILURE:
				Toast.makeText(MailActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case UIEventListener.EVENT_GET_DATA_FEFRESH_SUCCESS:
				HashMap<String, Object> map2 = (HashMap<String, Object>) msg.obj;
				if (map2 != null) {
					if ("1".equals(map2.get("req_code"))) {
						mailInfo = (MailInfo) map2.get("mailInfo");
						if (mailInfo != null) {
							setData();
						}
					} else {
						Toast.makeText(MailActivity.this, (String) map2.get("req_mess") == null ? "返回信息错误" : (map2.get("req_mess") + ""),
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mail);
		ivBackIV = (ImageView) findViewById(R.id.home_back_iv);
		ivBackIV.setOnClickListener(this);

		ivSend = (TextImageView) findViewById(R.id.mail_send_bt);
		ivSend.setOnClickListener(this);
		ivSend.setText("发送");
		titleText = (TextView) findViewById(R.id.mail_title_tv);
		mailType = getIntent().getIntExtra("mailType", 0);
		switch (mailType) {
		case 0:
			titleText.setText("写邮件");
			break;
		case 1:
			titleText.setText("回复邮件");
			break;
		case 2:
			titleText.setText("回复全部邮件");
			break;
		case 3:
			titleText.setText("转发邮件");
			break;
		case 4:
			titleText.setText("新邮件");
			break;

		default:
			break;
		}

		// 附件
		attListView = (ListView) findViewById(R.id.attListView);
		fujianSwitch = (LinearLayout) findViewById(R.id.ll_mail_info_fujian_switch);
		fujianItem = (RelativeLayout) findViewById(R.id.rl_mail_info_fujian_item);
		fujianNum = (TextView) findViewById(R.id.tv_fujian_num);
		fujianArrow = (ImageView) findViewById(R.id.img_mail_info_fujian_arrow);
		fujianContent = (LinearLayout) findViewById(R.id.ll_mail_info_fujian_content);
		// 为附件的条件添加点击事件
		fujianItem.setOnClickListener(this);

		recAddrADD = (ImageView) findViewById(R.id.mail_recAddr_add_iv);
		mailccADD = (ImageView) findViewById(R.id.mail_mailcc_add_iv);
		mailBccADD = (ImageView) findViewById(R.id.mail_mailBcc_add_iv);
		mail_add_attachment = (ImageView) findViewById(R.id.mail_add_attachment);
		recAddrADD.setOnClickListener(this);
		mailccADD.setOnClickListener(this);
		mailBccADD.setOnClickListener(this);
		mail_add_attachment.setOnClickListener(this);

		recAddrET = (EditText) findViewById(R.id.mail_recAddr_et);
		mailCcET = (EditText) findViewById(R.id.mail_mailcc_et);
		mailBccET = (EditText) findViewById(R.id.mail_mailBcc_et);
		subjectET = (EditText) findViewById(R.id.mail_subjec_et);
		contentET = (EditText) findViewById(R.id.mail_content_et);

		markLayout = (LinearLayout) findViewById(R.id.mail_mask_view);
		markLayout.setVisibility(View.GONE);
		markLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (markLayout.isShown()) {
					menuLayout.startAnimation(hideMenuAnimation);
					return true;
				}
				return true;
			}
		});
		menuLayout = (LinearLayout) findViewById(R.id.mail_menu_layout);
		menuLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});
		menuLayout.setVisibility(View.GONE);

		menuSaveBackBT = (RelativeLayout) findViewById(R.id.mail_menu_save_back_bt);
		menuBackBT = (RelativeLayout) findViewById(R.id.mail_menu_back_bt);
		menuCancleBT = (RelativeLayout) findViewById(R.id.mail_info_menu_cancle_bt);
		menuSaveBackBT.setOnClickListener(this);
		menuBackBT.setOnClickListener(this);
		menuCancleBT.setOnClickListener(this);

		showMenuAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1,
				Animation.RELATIVE_TO_SELF, 0);
		showMenuAnimation.setDuration(300);
		hideMenuAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
				Animation.RELATIVE_TO_SELF, 1);
		hideMenuAnimation.setDuration(300);
		showMenuAnimation.setAnimationListener(this);
		hideMenuAnimation.setAnimationListener(this);
		getData = getIntent().getBooleanExtra("getData", false);
		isSend = getIntent().getBooleanExtra("isSend", false);
		String receiveName = getIntent().getStringExtra("receiveName");
		if (!TextUtils.isEmpty(receiveName)) {
			recAddrET.setText(receiveName);
		}

		if (getData) {
			getMailInfoRequest();
		} else {
			mailInfo = (MailInfo) getIntent().getSerializableExtra("mailInfo");
			if (mailInfo != null) {
				setData();
			} else {
				findViewById(R.id.mail_webview_out_layout).setVisibility(View.GONE);
			}
		}
	}

	private void getMailInfoRequest() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("invoke", "getImailDetail");
		map.put("userCode", MailApplication.userCode);
		map.put("password", MailApplication.passWord);
		map.put("imailId", getIntent().getStringExtra("mailId"));
		new HttpManage(MailActivity.this, MailActivity.this, map, 2);
		dialog = Utils.createProgressDialog(this, Utils.getLoadingMessage(MailActivity.this, "加载中..."));
		dialog.show();
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void setData() {
		// findViewById(R.id.mail_webview_out_layout).setVisibility(View.VISIBLE);
		preContent = (MyWebView) findViewById(R.id.mail_pre_content);
		if (mailType == 1 || mailType == 2) {
			if (mailType == 1) {
				recAddrET.setText(mailInfo.from);
			} else if (mailType == 2) {
				recAddrET.setText(mailInfo.from + ";" + mailInfo.mailCc + mailInfo.mailBcc + mailInfo.recAddr);
			}
			subjectET.setText("回复:" + mailInfo.subject);
			if (!isSend) {
				preContentStr = "-------- 原始邮件 --------<br/></p>在" + mailInfo.sendDate + "　" + mailInfo.mailUserId + "(" + mailInfo.from
						+ ")写道：<br/>" + mailInfo.plainContent;
			} else {
				preContentStr = "-------- 原始邮件 --------<br/></p>在" + mailInfo.sendDate + "　" + mailInfo.mailUserId + "(" + mailInfo.from
						+ ")写道：<br/>" + mailInfo.plainContent + (!"".equals(mailInfo.preContent) ? "<br/></p>" : "") + mailInfo.preContent;
			}
			preContent.setVisibility(View.VISIBLE);
			preContent.getSettings().setJavaScriptEnabled(true);
			preContent.getSettings().setDefaultTextEncodingName("UTF-8");
			preContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
			preContent.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
			preContent.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
			preContent.loadDataWithBaseURL("about:blank", preContentStr, "text/html", "UTF-8", null);
			preContent.requestRectangleOnScreen(new Rect(0, 0, 10, 10));
		} else if (mailType == 4) {
			recAddrET.setText(mailInfo.recAddr);
			mailCcET.setText(mailInfo.mailCc);
			mailBccET.setText(mailInfo.mailBcc);
			subjectET.setText(mailInfo.subject);
			contentET.setText(mailInfo.plainContent);
			if (mailInfo.preContent != null && !"".equals(mailInfo.preContent)) {
				preContentStr = mailInfo.preContent;
				preContent.setVisibility(View.VISIBLE);
				preContent.getSettings().setJavaScriptEnabled(true);
				preContent.getSettings().setDefaultTextEncodingName("UTF-8");
				preContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
				preContent.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
				preContent.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
				preContent.loadDataWithBaseURL("about:blank", preContentStr, "text/html", "UTF-8", null);
				preContent.requestRectangleOnScreen(new Rect(0, 0, 10, 10));
			} else {
				preContent.setVisibility(View.GONE);
			}
		} else if (mailType == 3) {
			subjectET.setText("转发:" + mailInfo.subject);
			if (!isSend) {
				preContentStr = "-------- 原始邮件 --------<br/></p>在" + mailInfo.sendDate + "　" + mailInfo.mailUserId + "(" + mailInfo.from
						+ ")写道：<br/>" + mailInfo.plainContent;
			} else {
				preContentStr = "-------- 原始邮件 --------<br/></p>在" + mailInfo.sendDate + "　" + mailInfo.mailUserId + "(" + mailInfo.from
						+ ")写道：<br/>" + mailInfo.plainContent + (!"".equals(mailInfo.preContent) ? "<br/></p>" : "") + mailInfo.preContent;
			}
			// preContentStr =
			// "-------- 原始邮件 --------<br/></p>在"+mailInfo.sendDate
			// +"　"+mailInfo.mailUserId+"("+mailInfo.from+")写道：<br/>"
			// +mailInfo.plainContent;
			preContent.setVisibility(View.VISIBLE);
			preContent.getSettings().setJavaScriptEnabled(true);
			preContent.getSettings().setDefaultTextEncodingName("UTF-8");
			preContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
			preContent.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
			preContent.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
			preContent.loadDataWithBaseURL("about:blank", preContentStr, "text/html", "UTF-8", null);
			// 初始化附件
			initFujian();

		} else {
			// preContent.setVisibility(View.GONE);
			findViewById(R.id.mail_webview_out_layout).setVisibility(View.GONE);
		}
		handler.postDelayed(new WebViewOpenRunnable(), 200);
		handler.postDelayed(new WebViewCloseRunnable(), 400);
	}

	private class WebViewOpenRunnable implements Runnable {

		@Override
		public void run() {
			if (mailType == 3) {
				fujianArrow.setBackgroundResource(R.drawable.arrow_up_blue);
				fujianContent.setVisibility(View.VISIBLE);
			} else {
				fujianSwitch.setVisibility(View.VISIBLE);
			}

		}

	}

	private class WebViewCloseRunnable implements Runnable {

		@Override
		public void run() {
			if (mailType == 3) {
				fujianArrow.setBackgroundResource(R.drawable.arrow_down_blue);
				fujianContent.setVisibility(View.GONE);
			} else {
				fujianSwitch.setVisibility(View.GONE);
			}

		}

	}

	/**
	 * 初始化附件
	 */
	private void initFujian() {
		fujianSwitch.setVisibility(View.VISIBLE);
		fujianNum.setText("" + mailInfo.attachments.size());
		LinearLayout fujianView;
		TextView fujianName;
		ImageView fujianIcon, delete;
		fujianContent.setVisibility(View.GONE);
		for (int i = 0; i < mailInfo.attachments.size(); i++) {
			final String fujianStr = (String) mailInfo.attachments.get(i);
			fujianView = (LinearLayout) View.inflate(this, R.layout.fujian_delete_item, null);
			fujianName = (TextView) fujianView.findViewById(R.id.fujian_filename);
			fujianIcon = (ImageView) fujianView.findViewById(R.id.fujian_icon);
			delete = (ImageView) fujianView.findViewById(R.id.fujian_delete_bt);
			fujianName.setText(fujianStr);
			Utils.setFujianIcon(fujianIcon, fujianStr);

			final LinearLayout tempView = fujianView;
			delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					AlertDialog.Builder dialog = new AlertDialog.Builder(MailActivity.this).setTitle("删除提示").setMessage("确定删除附件：" + fujianStr)
							.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {

									try {
										fujianContent.removeView(tempView);
										String num = fujianNum.getText().toString().trim();
										int curNum = Integer.parseInt(num) - 1;
										fujianNum.setText("" + curNum);

										if (curNum == 0) {
											fujianSwitch.setVisibility(View.GONE);
										}
									} catch (Exception e) {
										Toast.makeText(MailActivity.this, "移除附件失败，请稍后再试", Toast.LENGTH_SHORT).show();
										dialog.dismiss();
									}

									dialog.dismiss();
								}
							}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
					dialog.show();
				}
			});

			// 添加分割线
			if (i > 0) {
				ImageView ivDevide = new ImageView(MailActivity.this);
				ivDevide.setBackgroundResource(R.drawable.listview_divider);

				fujianContent.addView(ivDevide);

				LayoutParams params = ivDevide.getLayoutParams();
				params.width = LayoutParams.FILL_PARENT;
				params.height = DensityUtil.dip2px(MailActivity.this, 1);
				ivDevide.setLayoutParams(params);
			}

			fujianContent.addView(fujianView);

		}
		// if (fujianContent != null) {
		// fujianContent.performClick();
		// fujianContent.performClick();
		// }
	}

	@Override
	public void onClick(View v) {
		if (v == ivBackIV) {
			// 如果键盘打开隐藏键盘
			hideSoftKeyboard();

			if (!"".equals(recAddrET.getText().toString().trim()) || !"".equals(mailCcET.getText().toString().trim())
					|| !"".equals(mailBccET.getText().toString().trim()) || !"".equals(subjectET.getText().toString().trim())
					|| !"".equals(contentET.getText().toString().trim())) {
				menuLayout.setVisibility(View.VISIBLE);
				menuLayout.startAnimation(showMenuAnimation);
			} else {
				finish();
			}
		} else if (v == fujianItem) {// 显示附件
			if (fujianContent.isShown()) {
				fujianArrow.setBackgroundResource(R.drawable.arrow_down_blue);
				fujianContent.setVisibility(View.GONE);
			} else {
				fujianArrow.setBackgroundResource(R.drawable.arrow_up_blue);
				fujianContent.setVisibility(View.VISIBLE);
			}
		} else if (v == ivSend) {
			String recAddrETStr = recAddrET.getText().toString().trim();
			if ("".equals(recAddrETStr)) {
				Toast.makeText(MailActivity.this, "收件人不能为空", Toast.LENGTH_SHORT).show();
				return;
			} else if ("".equals(subjectET.getText().toString().trim())) {
				Toast.makeText(MailActivity.this, "主题不能为空", Toast.LENGTH_SHORT).show();
				return;
			}
			String[] arr = new String[0];
			arr = fileList.toArray(arr);
			new HttpManage(MailActivity.this, MailActivity.this, getsendMailParams(), 1, arr);
			dialog = Utils.createProgressDialog(this, Utils.getLoadingMessage(MailActivity.this, "发送邮件中..."));
			dialog.show();
		} else if (v == menuCancleBT) {
			menuLayout.startAnimation(hideMenuAnimation);
		} else if (v == menuSaveBackBT) {
			if (mailInfo == null) {
				mailInfo = new MailInfo();
			}
			mailInfo.recAddr = recAddrET.getText().toString().trim();
			mailInfo.mailCc = mailCcET.getText().toString().trim();
			mailInfo.mailBcc = mailBccET.getText().toString().trim();
			mailInfo.subject = subjectET.getText().toString().trim();
			mailInfo.plainContent = contentET.getText().toString().trim();
			if (mailType == 1 || mailType == 2 || (mailType == 4 && mailInfo.preContent != null && !"".equals(mailInfo.preContent))) {
				mailInfo.preContent = "<br/><br/>" + preContentStr;
			}
			DBHandler db = new DBHandler(this);
			db.updateCaoGao(mailInfo);
			if (mailType == 4) {
				MailActivity.this.setResult(RESULT_OK);
			}
			finish();
		} else if (v == menuBackBT) {
			finish();
		} else if (v == recAddrADD) {
			selectMailAddress(requestCode_recAddrADD);
		} else if (v == mailccADD) {
			selectMailAddress(requestCode_mailccADD);
		} else if (v == mailBccADD) {
			selectMailAddress(requestCode_mailBccADD);
		} else if (v == mail_add_attachment) {
			Intent intent = new Intent(this, SearchFilesActivity.class);
			startActivityForResult(intent, requestCode_file);
		}
	}

	private static final int requestCode_recAddrADD = 1, requestCode_mailccADD = 2, requestCode_mailBccADD = 3, requestCode_file = 4;

	/**
	 * 
	 * @param type
	 *            1。收件、2。抄送、3。密送
	 */
	private void selectMailAddress(int type) {

		Intent qIntent = new Intent();
		qIntent.setAction("cn.ibm.moa.bmcc.portal.activity.ContactsSelect");
		List<ResolveInfo> apps = getPackageManager().queryIntentActivities(qIntent, 0);
		if (apps != null && apps.size() > 0) {
			Intent intent = new Intent();
			intent.setAction("cn.ibm.moa.bmcc.portal.activity.ContactsSelect");
			intent.putExtra("userName", MailApplication.userCode);
			intent.putExtra("password", MailApplication.passWord);
			intent.putExtra("from", MailApplication.from);
			try {
				startActivityForResult(intent, type);
			} catch (Exception e) {
			}

		} else {
			qIntent = new Intent();
			qIntent.setAction("com.ibm.moa.contact.select");
			qIntent.addCategory("android.intent.category.DEFAULT");
			apps = getPackageManager().queryIntentActivities(qIntent, 0);
			if (apps != null && apps.size() > 0) {
				Intent intent = new Intent("com.ibm.moa.contact.select");
				intent.putExtra("userName", MailApplication.userCode);
				intent.putExtra("password", MailApplication.passWord);
				intent.putExtra("from", MailApplication.from);
				try {
					startActivityForResult(intent, type);
				} catch (Exception e) {
					Toast.makeText(MailActivity.this, "请您在易办公中下载新版通讯录后再使用此功能！", Toast.LENGTH_SHORT).show();
				}

			} else {
				Toast.makeText(MailActivity.this, "请您在易办公中下载新版通讯录后再使用此功能！", Toast.LENGTH_SHORT).show();
			}
		}

	}

	/**
	 * 如果键盘打开隐藏键盘
	 */
	private void hideSoftKeyboard() {
		// 虚拟键盘隐藏 判断view是否为空
		View view = getWindow().peekDecorView();
		if (view != null) {// 隐藏虚拟键盘
			InputMethodManager inputmanger = (InputMethodManager) getSystemService(MailActivity.INPUT_METHOD_SERVICE);
			inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
		}
	}

	private HashMap<String, String> getsendMailParams() {
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("invoke", "sendMail");
		map.put("userCode", MailApplication.userCode);
		map.put("password", MailApplication.passWord);
		if (mailType == 3 && !isSend) {
			map.put("forwardMailID", mailInfo.mailId);
		}
		//
		String mailCcS = mailCcET.getText().toString().trim();
		String mailBccS = mailBccET.getText().toString().trim();
		String recAddrS = recAddrET.getText().toString().trim();
		mailCcS = mailCcS.replaceAll(";", ",");
		mailCcS = mailCcS.replaceAll("；", ",");
		mailBccS = mailBccS.replaceAll(";", ",");
		mailBccS = mailBccS.replaceAll("；", ",");
		recAddrS = recAddrS.replaceAll(";", ",");
		recAddrS = recAddrS.replaceAll("；", ",");
		if (mailInfo == null) {
			mailInfo = new MailInfo();
		}
		mailInfo.from = MailApplication.userCode + PropertiesUtils.singlton().getProperty("MAILPATH");
		mailInfo.setMailBcc(mailBccS);
		mailInfo.setMailCc(mailCcS);
		mailInfo.setRecAddr(recAddrS);
		if (mailType == 1 || mailType == 2 || mailType == 3 || mailType == 4) {
			mailInfo.setPlainContent(contentET.getText().toString().trim() + "<br/></p><br/></p>" + preContentStr);
		} else {
			mailInfo.setPlainContent(contentET.getText().toString().trim());
		}
		mailInfo.setSubject(subjectET.getText().toString().trim());

		String jsonString = JSON.toJSONString(mailInfo);
		// JSONObject obj = JSONObject.fromObject(mailInfo);
		map.put("mailInfoXML", jsonString);
		return map;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (markLayout.isShown()) {
				menuLayout.startAnimation(hideMenuAnimation);
				return true;
			}
			if (!"".equals(recAddrET.getText().toString().trim()) || !"".equals(mailCcET.getText().toString().trim())
					|| !"".equals(mailBccET.getText().toString().trim()) || !"".equals(subjectET.getText().toString().trim())
					|| !"".equals(contentET.getText().toString().trim())) {
				menuLayout.setVisibility(View.VISIBLE);
				menuLayout.startAnimation(showMenuAnimation);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onAnimationStart(Animation animation) {
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		if (animation == showMenuAnimation) {
			markLayout.setVisibility(View.VISIBLE);
			menuLayout.setVisibility(View.VISIBLE);
		} else if (animation == hideMenuAnimation) {
			markLayout.setVisibility(View.GONE);
			menuLayout.setVisibility(View.GONE);
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
	}

	@Override
	public void action(int actionCode, String resultStr, int httpFlag) {
		switch (actionCode) {
		case HttpRequestListener.EVENT_GET_DATA_SUCCESS:
			switch (httpFlag) {
			case 1:
				try {
					Log.i("lgs", "" + resultStr);
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_SUCCESS, ParserRequest.ParsSendMail(resultStr));
					moreMeg.sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FAILURE, "返回信息错误");
					moreMeg.sendToTarget();
				}
				break;
			case 2:
				try {
					Log.i("lgs", "" + resultStr);
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FEFRESH_SUCCESS, ParserRequest.ParsMailInfo(resultStr));
					moreMeg.sendToTarget();
				} catch (Exception e) {
					e.printStackTrace();
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FAILURE, "返回信息错误");
					moreMeg.sendToTarget();
				}
				break;
			}
			break;
		case HttpRequestListener.EVENT_GET_DATA_FAIL:
			Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FAILURE, "网络请求失败");
			moreMeg.sendToTarget();
			break;
		}

	}

	@Override
	@SuppressWarnings("unchecked")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case requestCode_recAddrADD:
				if (data != null && data.getSerializableExtra("selected") != null) {
					ArrayList<HashMap<String, String>> selected = (ArrayList<HashMap<String, String>>) data.getSerializableExtra("selected");
					String recAddrStr = recAddrET.getText().toString().trim();
					HashMap<String, String> map = null;
					for (int i = 0; i < selected.size(); i++) {
						map = selected.get(i);
						String email = map.get("hemail");
						if (email == null) {
							continue;
						}
						email = email.replace("@BMCC.COM.CN", "@bj.chinamobile.com");
						email = email.replace("@bmcc.com.cn", "@bj.chinamobile.com");
						if (!"".equals(email) && !recAddrStr.contains(email)) {
							if ("".equals(recAddrStr)) {
								recAddrStr += email;
							} else {
								recAddrStr += ";" + email;
							}
						}
					}
					recAddrET.setText(recAddrStr);
				}
				break;
			case requestCode_mailccADD:
				if (data != null && data.getSerializableExtra("selected") != null) {
					ArrayList<HashMap<String, String>> selected = (ArrayList<HashMap<String, String>>) data.getSerializableExtra("selected");
					String mailCCStr = mailCcET.getText().toString().trim();
					HashMap<String, String> map = null;
					for (int i = 0; i < selected.size(); i++) {
						map = selected.get(i);
						String email = map.get("hemail");
						if (email == null) {
							continue;
						}
						email = email.replace("@BMCC.COM.CN", "@bj.chinamobile.com");
						email = email.replace("@bmcc.com.cn", "@bj.chinamobile.com");
						if (email != null && !"".equals(email) && !mailCCStr.contains(email)) {
							if ("".equals(mailCCStr)) {
								mailCCStr += email;
							} else {
								mailCCStr += ";" + email;
							}
						}
					}
					mailCcET.setText(mailCCStr);
				}
				break;
			case requestCode_mailBccADD:
				if (data != null && data.getSerializableExtra("selected") != null) {
					ArrayList<HashMap<String, String>> selected = (ArrayList<HashMap<String, String>>) data.getSerializableExtra("selected");
					String mailBCCStr = mailBccET.getText().toString().trim();
					HashMap<String, String> map = null;
					for (int i = 0; i < selected.size(); i++) {
						map = selected.get(i);
						String email = map.get("hemail");
						if (email == null) {
							continue;
						}
						email = email.replace("@BMCC.COM.CN", "@bj.chinamobile.com");
						email = email.replace("@bmcc.com.cn", "@bj.chinamobile.com");
						if (email != null && !"".equals(email) && !mailBCCStr.contains(email)) {
							if ("".equals(mailBCCStr)) {
								mailBCCStr += email;
							} else {
								mailBCCStr += ";" + email;
							}
						}
					}
					mailBccET.setText(mailBCCStr);
				}
				break;
			case requestCode_file:
				String filepath = data.getStringExtra("filepath");
				if (filepath != null) {
					fileList.add(filepath);
				}
				loadAttachment();
				break;

			default:
				break;
			}

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private AttachmentAdapter attachmentAdapter;

	private void loadAttachment() {
		if (attachmentAdapter == null) {
			attachmentAdapter = new AttachmentAdapter(this, fileList);
			attListView.setAdapter(attachmentAdapter);
		} else {
			attachmentAdapter.notifyDataSetChanged();
		}
	}

	private static class AttachmentAdapter extends BaseAdapter {
		private Context context;
		private List<String> attList;
		private LayoutInflater mInflater;

		public AttachmentAdapter(Context context, List<String> attList) {
			this.context = context;
			this.attList = attList;
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return attList.size();
		}

		@Override
		public Object getItem(int position) {
			return attList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.fujian_delete_item, parent, false);
				holder = new ViewHolder();
				holder.fujian_icon = (ImageView) convertView.findViewById(R.id.fujian_icon);
				holder.fujian_delete_bt = (ImageView) convertView.findViewById(R.id.fujian_delete_bt);
				holder.fujian_filename = (TextView) convertView.findViewById(R.id.fujian_filename);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.fujian_icon.setVisibility(View.GONE);
			holder.fujian_filename.setText(attList.get(position));
			final int pos = position;
			holder.fujian_delete_bt.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					attList.remove(pos);
					notifyDataSetChanged();
				}
			});
			return convertView;
		}

		static class ViewHolder {
			ImageView fujian_icon;
			ImageView fujian_delete_bt;
			TextView fujian_filename;
		}

	}
}
